#!/usr/bin/python3 -tt

from cpfs.util import NamedFieldStruct
import cpfs
import tempfile, unittest

class NamedFieldStructTest(unittest.TestCase):

    def setUp(self):
        self.struct = NamedFieldStruct('TestStruct', [('hello', 'Q'), ('world', '7s')], 13)

    def runTest(self):
        blah = self.struct(world="yo")
        self.assertRaises(AttributeError, setattr, blah, 'hi', True)
        self.assertRaises(KeyError, blah.__getitem__, 'huh')
        blah['world'] = 'lolocaust'
        self.assertEqual(blah['world'], 'lolocaust')
        self.assertRaises(ValueError, blah.__getitem__, 'hello')
        blah['hello'] = ':)'
        self.assertEqual(blah['hello'], ':)')
        self.assertRaises(KeyError, blah.__setitem__, 'dict', None)
        self.assertRaises(ValueError, self.struct, 'too', 'many', 'args')

class Misc(unittest.TestCase):

    def test_splits_on_double_delims(self):
        self.assertEqual(
            '/some/path//crap'.split('/'),
            ['', 'some', 'path', '', 'crap'])

    def test_root_split(self):
        self.assertEqual('/'.split('/'), ['', ''])


class Filesystem(unittest.TestCase):

    def setUp(self):
        fd, self.path = tempfile.mkstemp()
        dev = open(fd, 'r+b')
        dev.truncate(999999)

    def runTest(self):
        cpfs.format(self.path)
        fs = cpfs.Filesystem(self.path)
        #def assert_raises_code(code, *args):
            #try:
                #args[0](*args[1:])
            #except cpfs.Error as e:
                #self.assertEqual(code, e.code)
        self.assertRaises(cpfs.error.InvalidPath, fs.single_op.stat, '')
        self.assertRaises(cpfs.error.InvalidPath, fs.single_op.stat, '//')
        self.assertRaises(cpfs.error.InvalidPath, fs.single_op.stat, 'lol!')
        self.assertRaises(TypeError, fs.single_op.stat, b'gay')
        self.assertRaises(cpfs.error.NoEntity, fs.single_op.stat, '/good/path\xff')
        inode = fs.single_op.stat('/')
        self.assertEqual(inode['perms'], 0o777)
        self.assertEqual(inode['type'], cpfs.INODE_TYPE_DIR)
        self.assertEqual(inode['ctime'], inode['mtime'])
        self.assertEqual(inode['mtime'], inode['atime'])
        self.assertRaises(cpfs.error.NoEntity, fs.single_op.stat, '/dir')
        with fs as ctx:
            ctx.mkdir('/dir', 0o731, 0, 0)
            inode = ctx.stat('/dir')
        self.assertEqual(inode['type'], cpfs.INODE_TYPE_DIR)

if __name__ == '__main__':
    # TODO use --buffer when it's added! (2.7/3.2), and maybe --debug
    cpfs.util.set_dev_logging()
    #unittest.main()
    tests = unittest.defaultTestLoader.loadTestsFromModule(__import__('__main__'))
    tests.debug()

